<template>
  <div class="publish-channel-container">
    <el-row :style="{ marginBottom: '20px' }">
      <el-col :span="8" class="left-col">
        <h4 style="margin-bottom: 4px">封面图</h4>
        <img :src="page.coverImg" :alt="page.title" />
      </el-col>
      <el-col :span="16" class="right-col">
        <el-row>
          <el-col :span="6">
            <img src="http://lowcode-backend.oss-cn-shenzhen.aliyuncs.com/lowcode-test/9tiL7h.png" :alt="page.title" />
          </el-col>
          <el-col :span="18" class="left-gap">
            <h4>{{ page.title }}</h4>
            <p>{{ page.desc }}</p>
          </el-col>
        </el-row>
        <el-tabs v-model="activePanel" :style="{ marginTop: '12px' }" type="card">
          <el-tab-pane label="发布为作品" name="channels">
            <el-row v-for="channel in channels" :key="channel.id" class="channel-item">
              <el-col :span="6">
                <canvas :id="`channel-barcode-${channel.id}`" class="barcode-container" />
              </el-col>
              <el-col :span="18" class="left-gap">
                <h4>{{ channel.name }}</h4>
                <el-row>
                  <el-col :span="18">
                    <el-input
                      :id="`channel-url-${channel.id}`"
                      :value="generateChannelURL(channel.id)"
                      :readonly="true"
                    />
                  </el-col>
                  <el-col :span="6">
                    <el-button class="copy-button" :data-clipboard-target="`#channel-url-${channel.id}`">
                      复制
                    </el-button>
                  </el-col>
                </el-row>
              </el-col>
              <div class="delete-area">
                <el-button type="danger" size="small" :disabled="deleteDisabled" @click="deleteChannel(channel.id)">
                  删除渠道
                </el-button>
              </div>
            </el-row>
            <el-form ref="channelForm" :inline="true" :style="{ marginTop: '20px' }" :model="form" :rules="rules">
              <el-form-item prop="channelName">
                <el-input v-model="form.channelName" placeholder="渠道名称"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="createChannel">创建新渠道</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="发布为模版" name="template">
            <el-row class="channel-item">
              <el-col :span="6">
                <canvas id="template-barcode" class="barcode-container" />
              </el-col>
              <el-col :span="18" class="left-gap">
                <h4>模版信息</h4>
                <el-row>
                  <el-col :span="18">
                    <el-input id="template-url" :value="generateTemplateURL()" :readonly="true" />
                  </el-col>
                  <el-col :span="6">
                    <el-button class="copy-button" data-clipboard-target="#template-url">复制</el-button>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <div class="template-submit">
              <el-button type="primary" @click="publishTemplate">发布模版</el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { useEditorStore } from '@/stores/editor'
import { baseH5URL } from '@/service/request'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { generateQRCode } from '@/utils/utils'
import { last } from 'lodash-es'
import Clipboard from 'clipboard'

const route = useRoute()
const editor = useEditorStore()

const page = computed(() => editor.page)
const channels = computed(() => editor.channels)
const deleteDisabled = computed(() => channels.value.length === 1)

const currentWorkId = route.params.id as string

const channelForm = ref<FormInstance>()
const activePanel = ref('channels')
const form = reactive({
  channelName: ''
})
const rules = reactive<FormRules>({
  channelName: [{ required: true, message: '标题不能为空', trigger: 'blur' }]
})

watch(
  channels,
  async (newChannels, oldChannels) => {
    if (newChannels.length > oldChannels.length) {
      // 取得最后一项的值
      const createdChannel = last(newChannels)
      if (createdChannel) {
        await generateQRCode(`channel-barcode-${createdChannel.id}`, generateChannelURL(createdChannel.id))
      }
    }
  },
  {
    flush: 'post' // 使侦听器延迟到组件渲染之后再执行
  }
)

onMounted(async () => {
  const clipboard = new Clipboard('.copy-button')
  clipboard.on('success', e => {
    ElMessage.success({ message: '复制成功', duration: 1000 })
    e.clearSelection() // 清楚插件自带的复制选中功能
  })

  channels.value.forEach(async channel => {
    try {
      await generateQRCode(`channel-barcode-${channel.id}`, generateChannelURL(channel.id))
    } catch (error) {
      console.log(error)
    }
  })
  try {
    await generateQRCode('template-barcode', generateTemplateURL())
  } catch (error) {
    console.log(error)
  }
})

const generateChannelURL = (channelId: string) => {
  return `${baseH5URL}/p/${page.value.id}-${page.value.uuid}?channel=${channelId}`
}

const generateTemplateURL = () => {
  return `${baseH5URL}/p/${page.value.id}-${page.value.uuid}`
}

const deleteChannel = (channelId: string) => {
  editor.deleteChannels(channelId)
}

const createChannel = async () => {
  const payload = {
    name: form.channelName,
    workId: parseInt(currentWorkId)
  }
  try {
    const valid = await channelForm.value.validate()
    if (valid) {
      await editor.createChannels(payload)
      form.channelName = ''
    }
  } catch (e) {
    console.error(e)
  }
}

const publishTemplate = async () => {
  await editor.publishTemplate(currentWorkId)
  ElMessage.success({ message: '发布模版成功', duration: 1000 })
}
</script>
<style lang="scss" scoped>
.left-col img {
  width: 80%;
}
.right-col img {
  width: 80px;
}
.left-gap {
  padding-left: 5px;
  height: 80px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.delete-area {
  position: absolute;
  top: 10px;
  right: 20px;
}
.channel-item {
  padding: 10px 0;
  border-bottom: 1px solid #efefef;
  position: relative;
}
.barcode-container {
  height: 80px;
  width: 80px;
}
.template-submit {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
